
//
//  YCLStatusDAL.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/28.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

//专门处理微博数据缓存和网络请求

/*
 1,查看本地是否有缓存数据如果有直接返回
 2.若有缓存则直接返回
 3.若没有去网络获取
 4.缓存获取的数据
 5.返回数据给调用者
 
 */

class YCLStatusDAL: NSObject {
    
    //单例
    static let sharedStatusDAL:YCLStatusDAL = YCLStatusDAL()
    
    //定义缓存时间 (单位s)
    private let overTime:NSTimeInterval = 60
    
    //删除过期微博
    func deleteCacheStatus() {
        
        //计算过期时间
        let overDate = NSDate.init(timeIntervalSinceNow: -overTime)
        
        //设置时间格式
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        //时间转字符串
        let overString = formatter.stringFromDate(overDate)
        YCLPrint("overString: \(overString)")
        
        //sql语句
        let sql = "DELETE FROM T_Status WHERE createTime < '\(overString)';"
        
        //删除过期微博
        YCLSQLiteManager.sharedSQLiteManager.dbQueue.inDatabase { (db) in
            
            do{
            
                try db.executeUpdate(sql, values: [])
                YCLPrint("清除缓存成功")
            }catch let error as NSError{
            
                YCLPrint("清除缓存失败")
                
            }
        }
        
        
        
        
    }
    
    
    //加载微博
    func loadStatus(since_id: Int64, max_id: Int64, callBack:(statusDicts: [[String: AnyObject]]? , error: NSError?) ->()) {
        
        //查看本地数据库是否保存数据
        loadCacheStatus(since_id, max_id: max_id) { (statusDicts) in
            
            if statusDicts != nil && statusDicts?.count != 0 {
                YCLPrint("本地有数据")
                callBack(statusDicts: statusDicts, error: nil)
                return
            }
        }
        
        //本地没有数据发送网络请求去网上下载
        // 1.urlString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 2.参数
        var parameters: [String : AnyObject] = ["access_token": YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount!.access_token!]
        
        //拼接参数
        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0 {
            
            parameters["max_id"] = NSNumber(longLong: max_id - 1)
        }
        
        
        YCLNetworkTool.sharedNetworkTool.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
            
            //YCLPrint("获取微博数据成功\(responseObject)")
            
            //将数据转化为模型
            if let dict = responseObject as? [String:AnyObject], let statusesDict = dict["statuses"] as? [[String:AnyObject]]{
                
                //保存数据到数据库
                self.saveCacheStatus(statusesDict)
                
                //将加载的数据给别人处理
                callBack(statusDicts: statusesDict, error: nil)
            }
            
        }) { (task, error) in
            
            YCLPrint("获取微博数据失败\(error)")
            
            callBack(statusDicts: nil, error: error)
        }
    }
    
    /*!
     //从本地数据库读取微博数据
     - parameter since_id: 下拉加载更多
     - parameter max_id:   上拉刷新
     - 从数据库加载微博模型后的回调
     */
    func loadCacheStatus(since_id: Int64, max_id: Int64, callback: (statusDicts: [[String: AnyObject]]?) -> ()){
        
        //用户uid一定存在
        let uid = YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount?.uid!
        
        assert(uid != nil, "用户uid不存在")
        
        //sql语句
        var sql = "SELECT status_id, status, user_id FROM T_Status \n" + "WHERE user_id = \(uid!) \n"
        
        //判断是上拉还是下拉
        //下拉刷新
        if since_id > 0 {
            
            sql += "AND status_id > \(since_id) \n"
        }
        
        if max_id > 0 {
            
            sql += "AND status_id < \(max_id) \n"
        }
        
        sql += "LIMIT 20;"
        
//        YCLPrint("sql: \(sql)")
        
        //加载缓存数据
        YCLSQLiteManager.sharedSQLiteManager.dbQueue.inDatabase { (db) in
            
            do {
                
                //执行sql语句
                let resultSet = try db.executeQuery(sql, values: [])
                
                //创建可变微博字典数组
                var statusDicts = [[String: AnyObject]]()
                
                //获取数据库中的数据
                while resultSet.next() {
                    
                    //获取的为字符串
                    let status = resultSet.stringForColumn("status")
                    
                    //sting -> data
                    let data = status.dataUsingEncoding(NSUTF8StringEncoding)
                    
                    //data -> json
                    let statusDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
                    
                    statusDicts.append(statusDict)
                }
                
                callback(statusDicts: statusDicts)
                
            }catch let error as NSError {
                
                YCLPrint("加载本地微博数据出错了\(error)")
                callback(statusDicts: nil)
            }
        }
    }
    //保存微博数据到数据库
    func saveCacheStatus(statuses: [[String: AnyObject]]) {
        
        //获取uid(必须存在)
        let uid = YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount?.uid
        
        //断言（uid必须存在）
        assert(uid != nil, "没有uid")
        
        //sql语句
        let sql = "INSERT INTO T_Status (status_id, status, user_id) VALUES (?, ?, ?)"
        
        YCLSQLiteManager.sharedSQLiteManager.dbQueue.inTransaction { (db, rollback) in
            
            do {
                
                //遍历微博模型数组
                for dict in statuses{
                    
                    let status_id = dict["id"] as! Int
                    
                    //微博字典不能直接存到数据库中
                    //字典->二进制->string
                    
                    let data = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
                    
                    let statusText = String.init(data: data, encoding: NSUTF8StringEncoding)
                    
                    try db.executeUpdate(sql, values: [status_id,statusText!,uid!])
                }
//                YCLPrint("保存了\(statuses.count)条微博")
                
            }catch let error as NSError{
                
                YCLPrint("保存微博出错了: \(error)")
            }
        }
    }
    
}


